﻿using System.Collections.Generic;
using System.Linq;

namespace NightskyMimic.Domain
{
    public class Zone
    {
        public List<Land> Lands { get; set; }

        public List<Creature> Creatures { get; set; }

        public List<Card> Graveyard { get; set; }

        public List<Card> Hand { get; set; }

        public Deck Library { get; set; }

        public int Life { get; set; }

        public Zone(Deck deck) 
        {
            Lands = new List<Land>();
            Creatures = new List<Creature>();
            Graveyard = new List<Card>();
            Hand = new List<Card>();
            Library = deck;
            Life = 20;
        }

        public void UntapAllCards() 
        {
            Creatures.ForEach(x => x.Tapped = false);
            Lands.ForEach(x => x.Tapped = false);
        }

        public void DrawCard() 
        {
            Card card = Library.Pick();
            Hand.Add(card);
            if (Hand.Count > 4)
                removeCardFromHand();
        }

        private void removeCardFromHand()
        {
            //if a have lots of lands (3) remove land
            if (Hand.Count(x => x is Land) >= 3)
            {
                Card toRemove = Hand.First(x => x is Land);
                //TODO: graveyard must accept lands
                Hand.Remove(toRemove);
            }
            //remove weakest creature
            else 
            {
                List<Creature> c = Hand.Where(x => x is Creature).Select(x => x as Creature).ToList();

                Creature weakest = c[0];
                int power = weakest.Power +  weakest.Toughness;

                foreach (Creature a in c) 
                {
                    if (a.Power + a.Toughness < power)
                    {
                        power = a.Power + a.Toughness;
                        weakest = a;
                    }
                }

                Hand.Remove(weakest);
            }
        }

        public void PutInPlay(Card card) 
        {
            //cartas só são jogadas da mão
            Hand.Remove(card);

            if (card is Creature)
                Creatures.Add((Creature)card);

            else
                Lands.Add((Land)card);
        }

        public void PutInGraveyard(Creature creature) 
        {
            Creatures.Remove(creature);
            Graveyard.Add(creature);
        }
    }
}